package pub.tbc.api.handler;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.cache.CacheProvider;
import pub.tbc.api.cache.ServiceCache;
import pub.tbc.api.helper.HttpResponseHelper;
import pub.tbc.api.service.ServiceInfo;

/**
 * 判断服务地址是否存在，不存在则直接返回不做后续处理
 *
 * @author tbc on 2017/3/30 17:03:41.
 */
@Slf4j
public class NoServiceAddressFilter extends AbstractHttpInboundHandler {
    private ServiceCache serviceCache = CacheProvider.getServiceCache();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        ServiceInfo serviceInfo = super.serviceMapping.map(msg);
        msg.retain();// 将引用计数增加1
        if (serviceCache.containService(serviceInfo.getServiceName())) {
            log.debug("找到服务[{}]的地址 => {}", serviceCache.get(serviceInfo.getServiceName()));

            ctx.fireChannelRead(msg);
        } else {
            ChannelFuture future = HttpResponseHelper.notFound(ctx, "无法获取该请求uri对应的服务地址");
            if (!HttpUtil.isKeepAlive(msg)) future.addListener(ChannelFutureListener.CLOSE);
        }


    }
}
